package com.nf.service;

import com.nf.dao.AccountMapper;
import com.nf.dao.RecordMapper;
import com.nf.entity.Account;
import com.nf.entity.Record;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private RecordMapper recordMapper;

    @Transactional
    public Account login(String userName, String password) {
        Account account = accountMapper.getAccountByUserName(userName);
        if (account==null){
            return null;
        }else if(  password.equals( account.getPassword() )  ){
            return account;
        }else {
            return null;
        }
    }

    @Transactional
    public Integer queryBanlanceById(Integer userid) {
        Account account = accountMapper.getAccountById(userid);
        if (account==null){
            return null;
        }else{
            return account.getBalance();
        }

    }
    @Transactional
    public boolean updatePassword(String newPassword, String oldPassword, Integer userId) {
        Account account = accountMapper.getAccountById(userId);
        if (account==null){
            return false;
        }
        if (  oldPassword.equals( account.getPassword() )&&(!oldPassword.equals(newPassword))  ){
            //做修改密码操作
            account.setPassword(newPassword);
            accountMapper.updateAccount(account);
            return true;
        }else{
            //和旧密码不一致
            return false;
        }

    }
    //存钱
    //1.判断user是否存在
    //2.判断账号的是否过了有效期
    //3.判断钱是否大于1万
    //4.添加1条流水记录（Record ，类型是存钱）
    //5.修改余额，自增
    @Transactional
    public boolean saveMoney(Integer money, Integer userId) {
        Account account = accountMapper.getAccountById(userId);
        //判断user是否存在
        if(account==null){
            return false;//这个方法已经结束了
        }
        //判断账号的是否过了有效期
        if((System.currentTimeMillis() - account.getValidDate().getTime() )>0){
            return false;
        }
        //判断钱是否大于1万
        if (money>10000||money<=0){
            return false;
        }
        //添加1条流水记录
        Record record = new Record();
        //record.setId(1);//此行代码是不需要，因为数据库是自增的【以后还要oracle是怎么玩的】
        System.out.println("插入之前record id："+record.getId());
        record.setUserId(userId);
        record.setM(money);
        record.setType(1);
        record.setDay(new Date());
        record.setDes("人民币存款");
        recordMapper.addRecord(record);
        System.out.println("插入之后record id："+record.getId());
        //return false;
        //修改余额，自增
        int money_new = account.getBalance() + money;
        account.setBalance(money_new);
        //由面向过程的思维，想着修改余额，升级到面向对象的思维，修改account这个账号对象所有状态（自然就包含了余额这个字段）
        //年轻的我，总是想着，修改一个余额字段，最后，变成修改这个记录中所有的字段，性能不行。
        //牺牲忽略不计的性能，就可以让这个项目更加好扩展
        accountMapper.updateAccount(account);

        return true;
    }
    //取钱
    //1.检查userId的账号account是否存在
    //2.判断有效期
    //3.判断余额是否足够
    //4.1次最多只能取2000元
    //5.每天只能取5次
    //6.每天上限是8000元
    //7.每次手续费1%,上限是5元
    //8.插入2条流水记录（本金，手续费）
    //9.余额减少
    public boolean getMoney(Integer money, Integer userId) {
        Account account = accountMapper.getAccountById(userId);
        //1.判断user是否存在
        if(account==null){
            return false;//这个方法已经结束了
        }
        //2.判断账号的是否过了有效期
        if((System.currentTimeMillis() - account.getValidDate().getTime() )>0){
            return false;
        }
        //3.判断余额是否足够
        if (money>account.getBalance()){
            return false;
        }
        //4.1次最多只能取2000元
        if(money>2000){
            return false;
        }
        //5.每天只能取5次
        List<Record> recordList = recordMapper.queryGetMoneyRecord(userId, new java.sql.Date(System.currentTimeMillis()));
        System.out.println("recordList:"+recordList);
        if (recordList.size()>=5){
            return false;
        }
        //6.每天上限是8000元
        int getMoneyCount = 0;
        for (Record r1:recordList){
            getMoneyCount = getMoneyCount + r1.getM();
        }
        if(getMoneyCount>=8000){
            return false;
        }
        //算手续费：每次手续费1%,上限是5元
        int poundage = money/100;
        if (poundage>5){
            poundage = 5;
        }
        //8.插入2条流水记录（本金，手续费）
        Record principalRecord = new Record();
        principalRecord.setUserId(userId);
        principalRecord.setM(money);
        principalRecord.setType(2);
        principalRecord.setDes("取钱[本金]"+money);
        principalRecord.setDay(new java.util.Date());
        recordMapper.addRecord(principalRecord);

        Record poundageRecord = new Record();
        poundageRecord.setUserId(userId);
        poundageRecord.setM(poundage);
        poundageRecord.setType(2);
        poundageRecord.setDes("取钱[手续费]"+poundage);
        poundageRecord.setDay(new java.util.Date());
        recordMapper.addRecord(poundageRecord);

        //9.余额减少
        int balance_new = account.getBalance() - money - poundage;
        account.setBalance(balance_new);
        accountMapper.updateAccount(account);
        return true;
    }

    //1.判断当前用户是否存在
    //2.判断目标用户是否存在
    //3.判断当前用户是否超过了有效期
    //4.判断目标用户是否超过了有效期
    //5.算手续费：每次手续费1%,上限是5元
    //6.当前用户余额是否足够（本金+手续费）
    //7.一次最多转500元
    //8.当天最多转2000元（没有次数限制）
    //9.插入转出记录
    //10.插入转出钱的手续费的记录
    //11.插入转入记录
    //12.修改当前用户的余额
    //13.修改目标用户的余额
    public boolean transMoney(Integer money, Integer userIdDest, Integer userIdMyself) {
        Account account_current = accountMapper.getAccountById(userIdMyself);
        Account account_dest = accountMapper.getAccountById(userIdDest);

        //1.判断当前用户是否存在
        if(account_current==null){
            return false;//这个方法已经结束了
        }
        //2.判断目标用户是否存在
        if(account_dest==null){
            return false;//这个方法已经结束了
        }
        //3.判断当前用户是否超过了有效期
        if((System.currentTimeMillis() - account_current.getValidDate().getTime() )>0){
            return false;
        }
        //4.判断目标用户是否超过了有效期
        if((System.currentTimeMillis() - account_dest.getValidDate().getTime() )>0){
            return false;
        }
        //5.算手续费：每次手续费1%,上限是5元
        int poundage = money/100;
        if (poundage>5){
            poundage = 5;
        }
        //6.当前用户余额是否足够（本金+手续费）
        if (account_current.getBalance()<(money+poundage)){
            System.out.println("余额不足");
            return false;
        }
        //7.一次最多转500元
        if(money>500){
            return  false;
        }
        //8.当天最多转2000元（没有次数限制）
        //8.1取出所有的记录
        List<Record> recordList = recordMapper.queryTransOutRecord(userIdMyself, new java.sql.Date(System.currentTimeMillis()));
        //8.2遍历所有的记录，统计一下一共转了多少钱
        int money_transOut =0;
        for (Record r:recordList){
            money_transOut+=r.getM();
        }
        //8.3判断
        if(money_transOut>2000){
            return false;
        }
        //9.插入转出记录
        //9.1定义记录实体类
        Record record_transOut = new Record();
        record_transOut.setUserId(userIdMyself);
        record_transOut.setM(money);
        record_transOut.setDay(new java.util.Date());
        record_transOut.setType(4);
        record_transOut.setDes("转出[本金]");

        //9.2通过dao层api，把实体类插入到数据库去
        recordMapper.addRecord(record_transOut);
        System.out.println("记录"+record_transOut);

        //10.插入转出钱的手续费的记录
        Record record_transOut_poundage = new Record();
        record_transOut_poundage.setUserId(userIdMyself);
        record_transOut_poundage.setM(poundage);
        record_transOut_poundage.setDay(new java.util.Date());
        record_transOut_poundage.setType(5);
        record_transOut_poundage.setDes("转出[手续费]");
        recordMapper.addRecord(record_transOut_poundage);

        //11.插入转入记录(没有手续费)
        Record record_transIn = new Record();
        record_transIn.setUserId(userIdDest);
        record_transIn.setM(money);
        record_transIn.setDay(new java.util.Date());
        record_transIn.setType(3);
        record_transIn.setDes("转入[来自："+userIdMyself+"("+account_current.getUserName()+")]");
        recordMapper.addRecord(record_transIn);

        //12.修改当前用户的余额
        account_current.setBalance(account_current.getBalance()-money-poundage);
        accountMapper.updateAccount(account_current);

        //13.修改目标用户的余额
        account_dest.setBalance(account_dest.getBalance()+money);
        accountMapper.updateAccount(account_dest);
        return true;
    }
}
